package com.greenyoung.pwiki.elindex.utils;

import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class File2Base64 {

    /**
     * 从云端地址取出pdf文件，将其转化成base64
     * @param fileUrl 云端oss地址
     * @return 文件的base64字符串
     * @throws IOException
     */
    public static String doIt(String fileUrl) throws IOException {
        InputStream is = null;
        String url = fileUrl;
        URL url2 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
        conn.setDoInput(true);
        conn.connect();
        is = conn.getInputStream();

        byte[] data = null;
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new BASE64Encoder().encode(data).replace("\n", "").replace("\r", "");
    }
}
